using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Entities.Serialization;
using Unity.Mathematics;
using Unity.Scenes;
using Unity.Transforms;
using UnityEngine;
using UnityEngine.InputSystem.EnhancedTouch;
using UnityEngine.UIElements;

namespace LS
{
    public enum PrefabTag
    {
        SelectionObject

    }

    public class PrefabLoaderAuthoring : MonoBehaviour
    {
        public PrefabTag prefabTag;
        public GameObject selectionPrefab;
        //public string selectionPrefab;
        public bool usePrefabPosition;
        public bool usePrefabRotation;
        public bool usePrefabScale;

        private void Awake()
        {
            Debug.Log("PrefabLoaderAuthoring.Awake");
        }
    }

    public class PrefabsLoaderBaker : Baker<PrefabLoaderAuthoring>
    {
        public override void Bake(PrefabLoaderAuthoring authoring)
        {
            Entity ent = GetEntity(TransformUsageFlags.Dynamic);
            //GameObject prefab = UnityProfabsReference.Instance?.GetPrefab(authoring.selectionPrefab);
            GameObject prefab = authoring.selectionPrefab;
            Debug.Log("PrefabLoaderBaker.Bake");
            var loaderComponent = new PrefabLoaderStatusComponent()
            {
                LoadStep = 1,
                PrefabTag = authoring.prefabTag,
                Prefab = prefab != null? GetEntity(prefab, TransformUsageFlags.Dynamic):default,
                transformInitializeState = new TransformInitializeState()
                {
                    usePrefabPosition = authoring.usePrefabPosition,
                    usePrefabRotation = authoring.usePrefabRotation,
                    usePrefabScale = authoring.usePrefabScale,
                    prefabPosition = prefab!= null? prefab.transform.position:default,
                    prefabRotation = prefab != null ? prefab.transform.rotation:default,
                    prefabScale = prefab != null ? prefab.transform.localScale:default,
                }
            };
            AddComponent(ent, loaderComponent);
        }
    }

    [Serializable]
    public struct TransformInitializeState
    {
        public bool usePrefabPosition;
        public float3 prefabPosition;

        public bool usePrefabRotation;
        public quaternion prefabRotation;

        public bool usePrefabScale;
        public float3 prefabScale;
    }

    public struct PrefabLoaderStatusComponent : IComponentData
    {
        public PrefabTag PrefabTag;
        /// <summary>
        /// 0未操作，1加载中，2加载完成,3生成完成
        /// </summary>
        public int LoadStep;
        public Entity Prefab;
        public TransformInitializeState transformInitializeState;
    }

    [BurstCompile]
    public partial struct PrefabsLoaderSystem : ISystem
    {
        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            var ecb = new EntityCommandBuffer(Allocator.Temp);
            foreach (var rLoader in
                SystemAPI.Query<RefRW<PrefabLoaderStatusComponent>>())
            {
                if (rLoader.ValueRO.LoadStep == 1)
                {
                    rLoader.ValueRW.LoadStep = 2;
                    if (rLoader.ValueRO.PrefabTag == PrefabTag.SelectionObject)
                    {
                        CreateSelectionPrefabs(ref ecb, rLoader);
                    }
                }
            }

            ecb.Playback(state.EntityManager);
            ecb.Dispose();
        }

        [BurstCompile]
        public void CreateSelectionPrefabs(ref EntityCommandBuffer commandBuffer, RefRW<PrefabLoaderStatusComponent> loader)
        {
            for (int x = 0; x < 100; x++)
            {
                for (int y = 0; y < 100; y++)
                {
                    var instance = commandBuffer.Instantiate(loader.ValueRO.Prefab);
                    var tsiState = loader.ValueRO.transformInitializeState;
                    var transform = LocalTransform.FromPositionRotation(
                            tsiState.usePrefabPosition ? tsiState.prefabPosition : new float3(x - 50, 0, y - 50),
                            tsiState.usePrefabRotation ? tsiState.prefabRotation : quaternion.identity);
                    bool enablePostScale = false;

                    if (tsiState.usePrefabScale)
                    {
                        if (tsiState.prefabScale.x == tsiState.prefabScale.y && tsiState.prefabScale.y == tsiState.prefabScale.z)
                        {
                            transform.Scale = tsiState.prefabScale.x;
                        }
                        else
                        {
                            enablePostScale = true;
                        }
                    }
                    commandBuffer.SetComponent(instance, transform);
                    if (enablePostScale)
                    {
                        commandBuffer.AddComponent(instance, new PostTransformMatrix() { Value = float4x4.Scale(tsiState.prefabScale) });
                    }
                }
            }
            loader.ValueRW.LoadStep = 3;
        }
    }
}
